package com.zhiyou100.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.sun.org.apache.regexp.internal.RE;
import com.zhiyou100.entity.Exam;
import com.zhiyou100.entity.PageInfo;
import com.zhiyou100.entity.ResponseEntity;
import com.zhiyou100.entity.Teacher;
import com.zhiyou100.service.ExamService;
import com.zhiyou100.service.TeacherService;
import com.zhiyou100.util.excel.ExcelUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 老师 控制层
 * 登陆、上传考试
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-27 14:46
 */
@Controller
@ResponseBody
public class TeacherAction {

    private TeacherService teacherService;
    private ExamService examService;

    @Autowired
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @Autowired
    public void setExamService(ExamService examService) {
        this.examService = examService;
    }

    /**
     * 老师登陆
     *
     * @param from    接受 json 参数
     * @param request 放信息到域中
     * @param code    验证码
     * @return 响应
     */
    @PostMapping("/teacher/login.action")
    public ResponseEntity<Teacher> login(Teacher from, String code, HttpServletRequest request) {
        Console.log(from,code);
        // 从 Session 中取出 验证码对象
        final Object verificationCode = request.getSession().getAttribute("VerificationCode");
        if (ObjectUtil.isNull(verificationCode)) {
            // Session 中没有 验证码
            return new ResponseEntity<>(500, "没有验证码", from);
        } else {
            // 有验证码, 向上转型
            CircleCaptcha circleCaptcha = (CircleCaptcha) verificationCode;
            if (!circleCaptcha.verify(code)) {
                // 验证不通过
                return new ResponseEntity<>(500, "验证码错误", from);
            } else {
                if (ObjectUtil.isNull(from) || ObjectUtil.isNull(from.getId()) || ObjectUtil.isNull(from.getPassword())) {
                    // 参数为空，或者 id、 password 为空
                    return new ResponseEntity<>(500, "登陆失败！参数为空，或者 id、password 为空", from);
                }
                // 根据 id 获取一个老师
                final Teacher teacher = teacherService.selectOneByField("id", from.getId());
                if (ObjectUtil.isNull(teacher)) {
                    // 没有该 id
                    return new ResponseEntity<>(500, "登陆失败！id 错误", teacher);
                } else {
                    if (teacher.getPassword().equals(from.getPassword())) {
                        // 密码一致
                        request.getSession().setAttribute("teacher", teacher);
                        return new ResponseEntity<>(200, "登陆成功！", teacher);
                    } else {
                        // 密码错误
                        return new ResponseEntity<>(500, "登陆失败！密码 错误", teacher);
                    }
                }
            }
        }


    }

    /**
     * 读取一个 excel 文件，将 Exam 放入数据库中
     *
     * @param examExcel 文件
     * @return 响应
     */
    @PostMapping("/teacher/addExam.action")
    public ResponseEntity<Object> addExam(@RequestParam("examExcel") MultipartFile examExcel) {
        List<Exam> exams;
        try {
            // 设置 标题别名
            exams = new ExcelReader(examExcel.getInputStream(), 0)
                    .addHeaderAlias("考试id", "id")
                    .addHeaderAlias("考试时间", "time")
                    .addHeaderAlias("考试的题目", "topic")
                    .readAll(Exam.class);
            // forEach 存储到数据库中
            exams.forEach(examService::addOne);
        } catch (IOException e) {
            return new ResponseEntity<>(500, "添加失败,没有收到文件", null);
        }
        return new ResponseEntity<>(200, "添加成功", exams);
    }

    /**
     * 获取所有的考试 分页
     *
     * @return 200 响应
     */
    @GetMapping("/exam/getAll.action")
    public ResponseEntity<Object> getAll(String pageNumber, Integer pageSize) {

        int page;
        String nan = "NaN";
        if (nan.equals(pageNumber) || ObjectUtil.isNull(pageNumber)) {
            page = 1;
        } else {
            page = Integer.parseInt(pageNumber);
        }

        Console.error(("/exam/getAll.action pageNumber = " + pageNumber + " pageSize = " + pageSize));

        final PageInfo<Exam> pageInfo = new PageInfo<>();
        pageInfo.setCount(examService.getAll().size());
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNumber(page);
        pageInfo.setList(examService.listOfPaginationOrderByTime(pageInfo.getStartIndex(), pageInfo.getPageSize()));
        Console.error(pageInfo);
        return new ResponseEntity<>(200,
                "分页查询的所有考试（根据考试时间升序）",
                pageInfo);
    }

    /**
     * 获取所有考试不分页
     *
     * @return 所有考试
     */
    @GetMapping("/exam/listExam.action")
    public ResponseEntity<Object> listOfExam() {
        return new ResponseEntity<>(200, "list exam", examService.getAll());
    }

    /**
     * 添加一个考试功能
     *
     * @param exam 要添加的考试，RequestBody 修饰说明是 json 参数
     * @return 响应
     */
    @PutMapping("/exam/add.action")
    public ResponseEntity<Object> addExam(@RequestBody Exam exam) {
        examService.addOne(exam);
        return new ResponseEntity<>(200, "添加成功！", exam);
    }


    /**
     * 删除所有传入的 list 中的 id
     *
     * @param list 参数 list
     * @return 响应
     */
    @RequestMapping("/exam/delete.action")
    public ResponseEntity<Object> deleteExam(@RequestParam(required = false, value = "list[]") List<Integer> list) {
        Console.log(list);
        // [1, 2, 3, 6]
        // forEach 语法，遍历删除
        list.forEach(id -> examService.deleteOne(id));
        return new ResponseEntity<>(200, "删除成功！", list);
    }

    /**
     * 更新 exam 方法
     *
     * @param exam 要更新的 exam
     * @return 响应
     */
    @PutMapping("/exam/update.action")
    public ResponseEntity<Object> update(@RequestBody Exam exam) {
        examService.updateOne(exam);
        return new ResponseEntity<>(200, "更新成功！！", exam);
    }

    /**
     * 创建一个图片验证码，放入 Session 中
     *
     * @param request  request
     * @param response response
     */
    @SneakyThrows
    @GetMapping("/teacher/code.action")
    public void createVerificationCode(HttpServletRequest request, HttpServletResponse response) {

        // 设置响应图片
        response.setContentType("image/png");
        // 获 response  的输出流
        final ServletOutputStream outputStream = response.getOutputStream();
        // 创建一个验证码
        final CircleCaptcha lineCaptcha = CaptchaUtil.createCircleCaptcha(200, 100);


        // 放入 Session 域中
        request.getSession().setAttribute("VerificationCode", lineCaptcha);

        // 写出
        lineCaptcha.write(outputStream);
        // 刷新
        outputStream.flush();
        // 关流
        outputStream.close();
    }
}
